<?php


namespace app\cms\model;


use app\cms\community\lib\QueryModel;
use iflow\Response;

class userRoleModel extends QueryModel
{

    protected $table = 'user_role_table';

    // 获取用户权限
    public function getUserRole(int $user_id, $user_group_id): array
    {
        $role = $this->getUserRoleList($user_id);
        $role = array_merge($role, $this->getUserRoleList($user_group_id, 'user_group_id'));
        $roles = [];
        foreach ($role as $val) {
            $roles[] = $val['user_role'];
        }
        return $roles;
    }

    public function getUserRoleList(int $id, string $type = 'uid'): array
    {

        // 用户组权限默认调用 "user_role_table" 内 设置的权限
        if ($type === 'user_group_id') {
            $this->table = "user_role_table";
        }

        return $this->withJoin([
            'hasSysRole' => [
                'user_role_path' => 'user_role',
                'user_role_name' => 'user_role_name'
            ]
        ], 'LEFT') -> where([
            'id' => $id,
            'type' => $type,
        ]) -> select() -> toArray();
    }

    public function hasSysRole()
    {
        return $this->hasOne(sysRoleModel::class, 'user_role_id', 'user_role_id');
    }

    /**
     * 设置用户权限
     * @param int $userId
     * @param int $user_role_id
     * @param string $type
     * @return Response
     */
    public function setUserRoles(int $userId, int $user_role_id, string $type): Response
    {
        $role = $this->where([
            'id' => $userId,
            'user_role_id' => $user_role_id,
            'type' => $type
        ]) -> findOrEmpty();

        if ($role -> isExists()) return message() -> update_failed('权限已存在, 请勿重复添加');

        $create = self::create([
            'id' => $userId,
            'user_role_id' => $user_role_id,
            'type' => $type
        ]) -> toArray();
        return message() -> success('添加权限成功成功', $create);
    }

    /**
     * 移除用户权限
     * @param int $id
     * @param int $user_role_id
     * @param string $type
     * @return Response
     */
    public function deleteRole(int $id, int $user_role_id, string $type): Response
    {
        $del = $this->where([
            'user_role_id' => $user_role_id,
            'id' => $id,
            'type' => $type
        ]) -> delete();

        return $del ? message() -> success('删除成功') :
            message() -> update_failed('删除失败');
    }
}